package cn.gaily.edumsm.controller;

import cn.gaily.commonutils.R;
import cn.gaily.edumsm.service.MsmService;
import cn.gaily.edumsm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description = "短信接口")
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis获取验证码，如果获取到直接返回，取不到则进行发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //生成随机验证码
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        boolean success = msmService.send(map, phone);
        if(success) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else{
            return R.error().data("msg", "短信发送失败");
        }
    }
}
